//
//  MGNotiStateViewController.swift
//  mggz
//
//  Created by QinWei on 2018/4/23.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class MGNotiStateViewController: UIViewController {
    fileprivate var signOutAlertView:TWLAlertView?
    @IBOutlet weak var notiState: UILabel!
    
    @IBOutlet weak var notiView: UIView!
    
    @IBOutlet weak var stateButton: UIButton!
    
    @IBOutlet weak var attendanceLabel: UILabel!
    
    @IBOutlet weak var timeView: UIView!
    
    @IBOutlet weak var timeLabel: UILabel!
    
    @IBOutlet weak var ringSwitch: UISwitch!
    
    var timeStr:String? = "6"
    var isNotiOpen:Bool? = true
    var isRing:Bool? = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.getSignedMessage()
        self.currentNotificationSetting()
        
        let ringStr = LoginAuthenticationService.getupRingtone()
       // let shockStr = LoginAuthenticationService.getupShockSound()
        if ringStr == "1"{
            self.ringSwitch.setOn(true, animated: true)
        }else{
            self.ringSwitch.setOn(false, animated: true)
        }
       
        let notiTap = UITapGestureRecognizer(target: self, action: #selector(notiTapClick(_:)))
        self.notiView.addGestureRecognizer(notiTap)

        let timeTap = UITapGestureRecognizer(target: self, action: #selector(timeTapClick(_:)))
       self.timeView.addGestureRecognizer(timeTap)
        
    }
    @objc fileprivate func timeTapClick(_ tap:UITapGestureRecognizer){
        
        self.signOutAlertView = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let advanceSureView = NotiTimeSelectView(frame: CGRect(x: 0, y: 0, width: 250, height: 195))
        advanceSureView.cancelClick = {
            self.signOutAlertView?.cancleView()
        }
        advanceSureView.selectedMinitinues = { (value) in
            self.signOutAlertView?.cancleView()
            self.timeStr = value
            self.timeLabel.text = value
            self.setSignedMessageSet(true)
        }
    self.signOutAlertView?.initWithCustomView(advanceSureView, frame: CGRect(x: 0, y: 0, width: 250, height: 195))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.signOutAlertView!)
    
    }
    @objc fileprivate func notiTapClick(_ tap:UITapGestureRecognizer){
        if self.isNotiOpen == false{
        UIApplication.shared.openURL(URL.init(string: UIApplicationOpenSettingsURLString)!)
        }
    }
    fileprivate func getSignedMessage(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        
    LCAPiSubManager.request(.GetSignedMessageSet(AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
               
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let resultDic = jsonString["Result"] as? NSDictionary else{
                    return
                }
                let timeT = resultDic["MinutesLimit"] as? Int
                if (timeT != nil){
                self.timeLabel.text =  String(timeT!)
                }
              let signedState = resultDic["IsSignedMessage"] as? Bool
                if signedState == true{
                    self.isRing = true
                    self.stateButton.setTitle("关闭", for: .normal)
                    self.attendanceLabel.text = "已开启"
                    self.timeView.isHidden = false
                }
                if signedState == false{
                    self.isRing = false
                    self.stateButton.setTitle("开启", for: .normal)
                    self.attendanceLabel.text = "未开启"
                    self.timeView.isHidden = true
                }
                
            }
        }
    }
    fileprivate func currentNotificationSetting() {
        if (UIDevice.current.systemVersion as NSString).floatValue >= 8 {
            if let setting = UIApplication.shared.currentUserNotificationSettings {
                if setting.types == UIUserNotificationType.init(rawValue: 0) {
                    self.notiState.text = "去设置"
                    self.isNotiOpen = false
                }
                else {
                    self.notiState.text = "已开启"
                    self.isNotiOpen = true
                }
            }
            
        }
    }
    
    
    @IBAction func stateButtonClick(_ sender: Any) {
        if self.isRing == true{
            let alert  = UIAlertController(title: "提醒", message: "关闭考勤提醒后，如不及时签到签出将会影响您的工资核算!", preferredStyle: .alert)
            
            let cancel = UIAlertAction(title: "取消", style: .cancel) { (action) in
                
            }
            cancel .setValue(UIColor.init(white: 0.60, alpha: 1), forKey: "titleTextColor")
            
            let choose = UIAlertAction(title: "确定关闭", style: .default) { (action) in
               self.setSignedMessageSet(false)
            }
            choose .setValue(UIColor.init(red: 0.97, green: 0.43, blue: 0.38, alpha: 1), forKey: "titleTextColor")
            alert.addAction(cancel)
            alert.addAction(choose)
            self.present(alert, animated: true) {
                
            }
        }
        if self.isRing == false{
            self.setSignedMessageSet(true)
        }
    }
    
    fileprivate func setSignedMessageSet(_ state:Bool){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
    LCAPiSubManager.request(.SetSignedMessageSet(isSignedMessage: state, minutesLimit: self.timeStr!, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
               
                guard (jsonString["State"]) as! String == "OK" else{
                    
                    return
                }
                if state == true{
                    self.isRing = true
                    self.attendanceLabel.text = "已开启"
                    self.stateButton.setTitle("关闭", for: .normal)
                    self.timeView.isHidden = false
                }else{
                    self.stateButton.setTitle("开启", for: .normal)
                    self.attendanceLabel.text = "未开启"
                    self.isRing = false
                    self.timeView.isHidden = true
                }
                WWSuccess("设置成功!")
            }
        }
    }
    @IBAction func ringSwitchClick(_ sender: UISwitch) {
        if sender.isOn {
            LoginAuthenticationService.setupRingtone(ring: "1")
        }else{
           LoginAuthenticationService.setupRingtone(ring: "2")
        }
    }

}
